package service_book

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
	"tools-api/src/common/db/database"
	"tools-api/src/common/utils"
	"tools-api/src/jcj/model"
	"xorm.io/xorm"
)

// BookDetailAddOrUpdate 记账新增/修改
func BookDetailAddOrUpdate(detail model.BookDetail) (bool, string) {
	if detail.Id > 0 { // 修改
		err := detail.Update()
		if err != nil {
			return false, "修改失败"
		}
		return true, "修改成功"
	} else { // 新增
		detail = detail.Create()
		if detail.Id == 0 {
			return false, "添加失败"
		}
		return true, "添加成功"
	}
}

// BookDetailDelete 删除
func BookDetailDelete(uuid string, id int64) error {
	return model.BookDetail{}.Delete(uuid, id)
}

// GetDetailList 明细列表
func GetDetailList(uuid string, bookId int64, date string, monthStart int) gin.H {
	var list []model.BookDetailResult
	var payout, income float64
	_ = database.Session(database.JCJEngine.NewSession(), func(session *xorm.Session) error {
		dateStart, dateEnd, err := utils.CalculateStartDateRange(date, monthStart)
		if err != nil {
			return err
		}
		s := dateStart.Format("2006-01-02")
		e := dateEnd.Format("2006-01-02")
		// 同一个session中获取列表、数量
		list = model.BookDetail{}.GetListByUuid(session, uuid, bookId, 0, s, e)

		payout, income = model.BookDetail{}.GetSumMoney(session, uuid, bookId, s, e)
		return nil
	})

	return gin.H{
		"list":   list,
		"payout": payout,
		"income": income,
	}
}

// getRangeDate 返回闭合起始结束日期
func getRangeDate(yearMonth string, monthStart int) (string, string) {
	var ms string
	if monthStart > 9 {
		ms = fmt.Sprintf("%d", monthStart)
	} else {
		ms = fmt.Sprintf("0%d", monthStart)
	}
	dateStart := fmt.Sprintf("%s-%s", yearMonth, ms)
	t, _ := time.Parse("2006-01-02", dateStart)
	dateEnd := t.AddDate(0, 1, -1).Format("2006-01-02")
	return dateStart, dateEnd
}
